<template>
    <div class="white-box">
        <title-more title="系统设置" />
        <el-tabs v-model="tabName" @tab-click="handleTab">
            <el-tab-pane label="基础配置" name="0">
                <el-form ref="ruleRef" :model="ruleForm" :rules="ruleCheck" label-width="120px">
                    <el-form-item label="平台联系人" prop="name">
                        <el-input v-model.trim="ruleForm.name" clearable placeholder="请输入平台联系人姓名" />
                    </el-form-item>
                    <el-form-item label="手机号" prop="phone">
                        <el-input
                            v-model.trim="ruleForm.phone"
                            oninput="value=value.replace(/[^\d]/g,'')"
                            maxlength="11"
                            clearable
                            placeholder="请输入手机号"
                        />
                    </el-form-item>
                    <el-form-item label="会员中心" prop="member_center_picture" required>
                        <div class="img-box flexs-center" @click.stop="showImg = true" v-if="ruleForm.member_center_picture == ''">
                            <el-icon color="#999" size="26px">
                                <UploadFilled />
                            </el-icon>
                        </div>
                        <div class="img-selects" v-else>
                            <el-image
                                class="img-selects__pic"
                                :src="proxy.imgUrl + ruleForm.member_center_picture + '!img_400'"
                                :preview-src-list="srcList"
                                fit="cover"
                            />
                            <div class="img-del" @click.stop="delImg">
                                <el-icon size="14px" color="#fff"><CloseBold /></el-icon>
                            </div>
                        </div>
                    </el-form-item>
					<el-form-item label="操作提示" prop="operation_prompt" required>
						<div class="editor-box">
							<Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig"
								mode="default" />
							<Editor style="height: 440px; overflow-y: hidden" v-model="valueHtml" :defaultConfig="editorConfig"
								mode="default" @onCreated="handleCreated" />
						</div>
					</el-form-item>
                    <el-form-item>
                        <div class="flexs" style="margin-top: 30px">
                            <el-button type="primary" :loading="form_loading" @click="submitForm(ruleRef)">确认</el-button>
                            <el-button @click="resetForm(ruleRef)">重置</el-button>
                        </div>
                    </el-form-item>
                </el-form>
            </el-tab-pane>
            <el-tab-pane label="积分设置" name="1">
                <el-form ref="ruleTwoRef" :model="ruleTwoForm" :rules="ruleTwoCheck" label-width="120px">
                    <el-form-item label="积分抵扣比例" prop="deduction_ratio">
                        <el-input-number v-model="ruleTwoForm.deduction_ratio" :min="0" />
                        <div class="contentText">1人民币等于{{ruleTwoForm.deduction_ratio}}积分</div>
                    </el-form-item>
                    <el-form-item label="积分返现比例" prop="cash_back_ratio">
                        <el-input-number v-model="ruleTwoForm.cash_back_ratio" :step="0.1" :min="0" />
						<div class="contentText">
							订单完成根据商品金额返回 {{ruleTwoForm.cash_back_ratio}} %积分
						</div>
						
                    </el-form-item>
                    <el-form-item>
                        <div class="flexs" style="margin-top: 30px">
                            <el-button type="primary" :loading="form_loading" @click="submitTwoForm(ruleTwoRef)">确认</el-button>
                            <el-button @click="resetTwoForm(ruleTwoRef)">重置</el-button>
                        </div>
                    </el-form-item>
                </el-form>
            </el-tab-pane>
			
			<el-tab-pane label="配送设置" name="2">
			    <el-form ref="ruleRef2" :model="ruleForm2" :rules="ruleCheck2" label-width="120px">
			        <el-form-item label="配送范围" prop="range">
			            <el-input-number v-model="ruleForm2.range" :min="0" />
			            <div class="contentText">超出{{ruleForm2.range}}公里不配送，0为不限制</div>
			        </el-form-item>
			        <el-form-item label="起配公里" prop="start_distance">
			            <el-input-number v-model="ruleForm2.start_distance" :min="0" />
						<div class="contentText">
							计价时最低按{{ruleForm2.start_distance}}公里计算
						</div>
						
			        </el-form-item>
					<el-form-item label="起配价格" prop="start_price">
					    <el-input-number v-model="ruleForm2.start_price" :min="0" />
					    <div class="contentText">计价时最低按{{ruleForm2.start_price}}元计算</div>
					</el-form-item>
					<el-form-item label="超出价格" prop="exceed_price">
					    <el-input-number v-model="ruleForm2.exceed_price" :min="0" />
						<div class="contentText">
							超出{{ruleForm2.start_distance}}公里每1公里加{{ruleForm2.exceed_price}}元
						</div>
						
					</el-form-item>
					<el-form-item label="商家配送费" prop="store_price">
					    <el-input-number v-model="ruleForm2.store_price" :min="0" />
						<div class="contentText">
							每个商家加{{ruleForm2.store_price}}元
						</div>
						
					</el-form-item>
					<el-form-item label="全职优先" prop="priority">
					    <el-radio-group v-model="ruleForm2.priority" size="small">
					    	<el-radio-button :label="1">开启</el-radio-button>
					    	<el-radio-button :label="2">关闭</el-radio-button>
					    </el-radio-group>
					</el-form-item>
					<el-form-item label="全职保留" prop="priority_time" v-if="ruleForm2.priority==1">
					    <el-input-number v-model="ruleForm2.priority_time" :min="0" />
						<div class="contentText">
							超出{{ruleForm2.priority_time}}秒后兼职也可以接单
						</div>
					</el-form-item>
					
			        <el-form-item>
			            <div class="flexs" style="margin-top: 30px">
			                <el-button type="primary" :loading="form_loading" @click="submitTForm2(ruleRef2)">确认</el-button>
			                <el-button @click="resetForm2(ruleRef2)">重置</el-button>
			            </div>
			        </el-form-item>
			    </el-form>
			</el-tab-pane>
        </el-tabs>
    </div>

    <!-- 图片库 -->
    <picture-library :show="showImg" :select_multiple="false" @close="showImg = false" @select="selectImg"> </picture-library>

    <go-back />
</template>

<script setup>
import { getCurrentInstance, ref,shallowRef, onMounted, reactive,onBeforeUnmount  } from "vue"
import { UploadFilled, CloseBold } from "@element-plus/icons-vue"
import GoBack from "@components/GoBack.vue"
import TitleMore from "@components/title-more.vue"
import PictureLibrary from "@components/PictureLibrary.vue"
import "@wangeditor/editor/dist/css/style.css"
import {
		Editor,
		Toolbar
	} from "@wangeditor/editor-for-vue"
	
const { proxy } = getCurrentInstance()

onMounted(() => {
    getOne()
})

const tabName = ref("0")
const handleTab = (pane) => {
    tabName.value = pane.index
    pane.index == 0 && !ruleForm.name && !ruleForm.phone && getOne()
    pane.index == 1 && !ruleTwoForm.deduction_ratio && !ruleTwoForm.cash_back_ratio && getTwo()
	pane.index == 2 && !ruleForm2.start_distance && getPei()
}
//基础信息
function getOne() {
    proxy.$axios
        .get("admin/system/setting/get")
        .then((res) => {
            if (res.data.code == 0) {
                let result = res.data.data
                ruleForm.member_center_picture = result.member_center_picture
				valueHtml.value=result.operation_prompt
                ruleForm.operation_prompt = result.operation_prompt
                ruleForm.name = result.name
                ruleForm.phone = result.phone
            } else {
                proxy.$message({message:res.data.msg,type:"error"})
            }
        })
        .catch((err) => {})
}
//积分
function getTwo() {
    proxy.$axios
        .get("admin/integral/setting/get")
        .then((res) => {
            if (res.data.code == 0) {
                let result = res.data.data
				ruleTwoForm.cash_back_ratio=result.cash_back_ratio
				ruleTwoForm.deduction_ratio=result.deduction_ratio
            } else {
                proxy.$message({message:res.data.msg,type:"error"})
            }
        })
        .catch((err) => {})
}
//配送
function getPei() {
    proxy.$axios
        .get("admin/delivery/getDelivery")
        .then((res) => {
            if (res.data.code == 0) {
                let result = res.data.data
				ruleForm2.range=result.range
				ruleForm2.start_distance=result.start_distance
				ruleForm2.start_price=result.start_price
				ruleForm2.exceed_price=result.exceed_price
				ruleForm2.priority=result.priority
				ruleForm2.priority_time=result.priority_time
				ruleForm2.store_price=result.store_price
            } else {
                proxy.$message({message:res.data.msg,type:"error"})
            }
        })
        .catch((err) => {})
}

/**
 * 基础配置
 * @param {Boolean} form_loading 弹窗按钮状态
 * @property {Array} ruleRef 表单规则
 * @property {Object} ruleForm  表单字段
 * @property {Object} ruleCheck  表单提示
 */
const form_loading = ref(false)
const ruleRef = ref(null)
const ruleForm = reactive({
    name: "",
    phone: "",
    operation_prompt: "",
    member_center_picture: "",
})
const ruleCheck = reactive({
    name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
    phone: [{ required: true, validator: proxy.$util.validPhone, trigger: "blur" }],
    operation_prompt: [{ required: true, message: "请输入操作提示", trigger: "blur" }],
    member_center_picture: [{ required: true, message: "请上传会员中心图片", trigger: "change" }],
})
// 确认
const submitForm = (formEl) => {
    if (!formEl) return
    formEl.validate((valid, fields) => {
        if (valid) {
            form_loading.value = true
			let htmls = ""
			if (valueHtml.value) {
				htmls = valueHtml.value.replace(/\bhttps?:\/\/(.*?)\/+/gi, "") // 去除图片根域名以及根域名后面的'/'
			}
            let data = {
                name: ruleForm.name,
                phone: ruleForm.phone,
                operation_prompt: htmls,
                member_center_picture: ruleForm.member_center_picture,
            }
            proxy.$axios
                .post("admin/system/setting/update", data)
                .then((res) => {
                    form_loading.value = false
                    if (res.data.code == 0) {
                        proxy.$message({ message: "保存成功！", type: "success" })
                        getOne()
                    } else {
                        proxy.$message({message:res.data.msg,type:"error"})
                    }
                })
                .catch((err) => {
                    form_loading.value = false
                })
        }
    })
}
const resetForm = (formEl) => {
    if (!formEl) return
    formEl.resetFields()
}

/**
 * 积分设置
 * @param {Boolean} form_loading 弹窗按钮状态
 * @property {Array} ruleTwoRef 表单规则
 * @property {Object} ruleTwoForm  表单字段
 * @property {Object} ruleTwoCheck  表单提示
 */
const ruleTwoRef = ref(null)
const ruleTwoForm = reactive({
    deduction_ratio:0,
    cash_back_ratio:0,
})
const ruleTwoCheck = reactive({
    deduction_ratio: [{ required: true, message: "请输入积分抵扣比例", trigger: "blur" }],
    cash_back_ratio: [{ required: true, message: "请输入积分返现比例", trigger: "blur" }],
})
// 确认
const submitTwoForm = (formEl) => {
    if (!formEl) return
    formEl.validate((valid, fields) => {
        if (valid) {
            form_loading.value = true
            let data = ruleTwoForm
            proxy.$axios
                .post("admin/integral/setting/update", data)
                .then((res) => {
                    form_loading.value = false
                    if (res.data.code == 0) {
                        proxy.$message({ message: "保存成功！", type: "success" })
                        getTwo()
                    } else {
                        proxy.$message({message:res.data.msg,type:"error"})
                    }
                })
                .catch((err) => {
                    form_loading.value = false
                })
        }
    })
}
const resetTwoForm = (formEl) => {
    if (!formEl) return
    formEl.resetFields()
}

/**
 * 配送设置
 * @param {Boolean} form_loading 弹窗按钮状态
 * @property {Array} ruleTwoRef 表单规则
 * @property {Object} ruleTwoForm  表单字段
 * @property {Object} ruleTwoCheck  表单提示
 */
const ruleRef2 = ref(null)
const ruleForm2 = reactive({
    
	range:0,
	start_distance:0,
	start_price:0,
	exceed_price:0,
	priority:1,
	priority_time:0,
	store_price:0
})
const ruleCheck2 = reactive({
    range: [{ required: true, message: "请输入配送范围", trigger: "blur" }],
    start_distance: [{ required: true, message: "请输入起送公里", trigger: "blur" }],
	start_price: [{ required: true, message: "请输入起配价格", trigger: "blur" }],
	exceed_price: [{ required: true, message: "请输入超出价格", trigger: "blur" }],
	store_price:[{ required: true, message: "请输入商家配送费", trigger: "blur" }],
})
// 确认
const submitTForm2 = (formEl) => {
    if (!formEl) return
    formEl.validate((valid, fields) => {
        if (valid) {
            form_loading.value = true
            let data = ruleForm2
            proxy.$axios
                .post("admin/delivery/setDelivery", data)
                .then((res) => {
                    form_loading.value = false
                    if (res.data.code == 0) {
                        proxy.$message({ message: "保存成功！", type: "success" })
                        getPei()
                    } else {
                        proxy.$message({message:res.data.msg,type:"error"})
                    }
                })
                .catch((err) => {
                    form_loading.value = false
                })
        }
    })
}
const resetForm2 = (formEl) => {
    if (!formEl) return
    formEl.resetFields()
}

/**
 * 添加图片
 * @property {Boolean} showImg 显示图片库
 * @property {Function} selectImg 选择图片
 */
const showImg = ref(false)
const srcList = ref([])
const selectImg = (val) => {
	console.log("ruleForm.member_center_picture",val)
    showImg.value = false
    tabName.value == 0 && (ruleForm.member_center_picture = val[0].url)
    tabName.value == 0 && srcList.value.push(proxy.imgUrl + val[0].url)
	console.log("ruleForm.member_center_picture",ruleForm.member_center_picture)
}
const delImg = () => {
    tabName.value == 0 && (ruleForm.member_center_picture = '')
    tabName.value == 0 && (srcList.value = [])

    
}

/**
	 * 富文本编辑器
	 * @param {Object} editorConfig 编辑器配置
	 * @param {String} valueHtml 输入内容
	 * @param {Object} toolbarConfig 工具栏配置
	 * @param {Function} createEditor 创建编辑器
	 * @param {Function} createToolbar 创建工具栏
	 * @param {Function} handleChange 编辑器内容变化
	 */
	const editorRef = shallowRef() // 编辑器实例，必须用 shallowRef
	const valueHtml = ref("") // 内容 HTML
	const toolbarConfig = {
		// 排除不需要的菜单"group-video",
		excludeKeys: ["insertLink", "insertImage", "editImage", "viewImageLink",
			"emotion", "fullScreen", "group-video"
		],
	}
	const editorConfig = {
		placeholder: "请输入内容...",
		MENU_CONF: {}
	}
	const handleCreated = (editor) => {
		editorRef.value = editor // 记录 editor 实例，重要！
	}
	editorConfig.MENU_CONF["uploadImage"] = {
		// 自定义上传
		async customUpload(file, insertFn) {
			let data = new FormData()
			// data.append("from", "article")
			data.append("file", file)
			proxy.$axios
				.post("admin/upload/upload", data)
				.then((res) => {
					if (res.data.code == 0) {
						let url = proxy.imgUrl + res.data.data.pic
						insertFn(url) // 最后插入图片 insertFn(url, alt, href)，alt：描述，href:链接，后面非必填
					} else {
						proxy.$message({
							message: res.data.msg,
							type: "error"
						})
					}
				})
				.catch((err) => {})
		},
	}
	
// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
    const editor = editorRef.value
    if (editor == null) return
    editor.destroy()
})
</script>
<script>
export default {
    name: "CustomerSetup",
}
</script>

<style lang="less" scoped>
.el-form {
    margin-top: @margin-lg;
}

.contentText{
	color: #8F95A5;
	margin-left: 20px;
}
</style>
